﻿using log4net.Appender;
using log4net.Core;
using log4net.Filter;
using log4net.Layout;
using System;
using System.IO;

namespace MarkdEdit.Log
{
    /// <summary>
    ///
    /// https://www.jianshu.com/p/ff3c12678e13
    /// </summary>
    internal class Log4NetLogger : ILog
    {
        public static ILog Log { get; private set; }

        public const string RepName = "base";

        private static void InitLogger()
        {
            var infoFilter = new LevelRangeFilter();
            infoFilter.AcceptOnMatch = true;
            infoFilter.LevelMax = log4net.Core.Level.Fatal;
            infoFilter.LevelMin = log4net.Core.Level.All;
            infoFilter.ActivateOptions();
            string layoutFormat = "@Log Begin%newlineThread ID：[%thread]%newline%message%newlineLog End@%newline";
            layoutFormat = "%d [%t] %-5p  %c %r %n ***********%m%n %logger %n";
            var basepath = AppDomain.CurrentDomain.BaseDirectory;
            var LogDir = Path.Combine(basepath, "log");
            PatternLayout layout = new PatternLayout(layoutFormat);
            var domain = RepName;
            var repository = log4net.LogManager.CreateRepository(domain);
            repository.Threshold = Level.Info;

            var fileAppender = new RollingFileAppender();
            fileAppender.Name = domain + "_" + "Info" + "_FileAppender";
            fileAppender.File = System.IO.Path.Combine(LogDir, "Log4net-" + domain + "-");
            fileAppender.AppendToFile = true;
            fileAppender.RollingStyle = RollingFileAppender.RollingMode.Date;
            fileAppender.DatePattern = "yyyy-MM-dd'.log'";
            fileAppender.StaticLogFileName = false;
            fileAppender.Layout = layout;
            fileAppender.AddFilter(infoFilter);
            fileAppender.ActivateOptions();
            log4net.Config.BasicConfigurator.Configure(repository, fileAppender);
        }

        static Log4NetLogger()
        {
            InitLogger();
            Log = new Log4NetLogger();
        }

        public void Debug(string msg, Exception ex)
        {
            log4net.LogManager.GetLogger(RepName, this.GetCallingType().FullName).Debug(msg, ex);
        }

        public void Error(string msg, Exception ex)
        {
            log4net.LogManager.GetLogger(RepName, this.GetCallingType().FullName).Error(msg, ex);
        }

        public void Info(string msg, Exception ex)
        {
            log4net.LogManager.GetLogger(RepName, this.GetCallingType().FullName).Info(msg, ex);
        }

        public void Warn(string msg, Exception ex)
        {
            log4net.LogManager.GetLogger(RepName, this.GetCallingType().FullName).Warn(msg, ex);
        }
    }
}